import { warn } from "cc";
import { ListenerFunc } from "./EventMessage";

class EventData{
    public evnent!: string;
    public listener!: ListenerFunc;
    public object:any;
}
export class MessageManager {
    private events:Map<string,Array<EventData>> = new Map();

    /**
     * 注册全局监听事件
     * @param event 事件名称
     * @param listener 监听函数
     * @param object 监听对象
     */
    public on(event:string,listener:ListenerFunc,object:object):void {
        if (!event || !listener) {
            warn(`注册【${event}】事件失败，请检查参数是否正确！`)
           return; 
        }
        let eds = this.events.get(event);
        if (eds == null) {
            eds = []
            this.events.set(event,eds)
        }
        let length = eds.length;
        for (let i = 0; i < length; i++) {
            const bin = eds[i];
            if (bin.listener == listener && bin.object == object) {
                warn(`注册【${event}】事件失败，该事件已注册过！`)
            }
        }
        let data:EventData = new EventData();
        data.evnent = event;
        data.listener = listener;
        data.object = object;
        eds.push(data);
    }

    /**
     * 移除全局监听事件
     * @param event 事件名称
     * @param listener 监听函数
     * @param object 监听对象
     */

    public off(event:string,listener:ListenerFunc,object:object):void{
        let eds = this.events.get(event);
        if (eds == null ) {
            warn(`移除【${event}】事件失败，该事件未注册！`)
            return;
        }
        let length = eds.length;
        for (let i = 0; i < length; i++) {
            //获取到监听函数
            let bin:EventData = eds[i];
            if (bin.listener == listener && bin.object == object) {
                eds.splice(i,1);
                break;
            }
        }

        if (eds.length == 0) {
            this.events.delete(event);
        }
    }

    public dispathchEvent(event:string, ...args:any){
        //获取到监听函数
        let list  = this.events.get(event);
        if(list){
            let eds:Array<EventData>  = list.concat();
            let length = eds.length;
            for (let i = 0; i < length; i++) {
                let bin = eds[i];
                bin.listener.call(bin.object,event,...args);
            }
        }

    }




}

export const message = new MessageManager();